package com.example.springboot.exception;

import com.example.springboot.common.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice

public class GlobalException {

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result serviceException(ServiceException e) {
        return Result.error(Integer.parseInt(e.getCode()), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result globalException(Exception e) {
        e.printStackTrace();
        if (e instanceof MethodArgumentNotValidException) {
            Map<String, String> result = new HashMap<>();
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            for (ObjectError objectError : bindingResult.getAllErrors()) {
                FieldError fieldError = (FieldError) objectError;
                result.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Result.error(500, result.toString());
        }
        if (e instanceof BindException) {
            return Result.error(500, ((BindException) e).getBindingResult().getFieldError().getDefaultMessage());
        } else {

            return Result.error(500, e.getMessage());
        }

    }
}
